/**
 *
 * @param {Function} reducer
 * @param {object} preloadedState 初始状态
 * @param {Function} enhancer 中间件
 * @returns
 */
export function createStore(reducer, preloadedState, enhancer) {
  // 增强dispatch函数 start
  if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
    enhancer = preloadedState;
    preloadedState = undefined;
  }
  if (typeof enhancer !== "undefined") {
    // 判断 enhancer 不是一个函数
    if (typeof enhancer !== "function") {
      // 抛出一个异常 (enhancer 必须是一个函数)
      throw new Error("Expected the enhancer to be a function.");
    }
    // 调用 enhancer ,返回一个增强版的 store creator
    return enhancer(createStore)(reducer, preloadedState);
    // 函数柯里化
    // function enhancer(createStore) {
    //     return (reducer, preloadedState) => {
    //         return createStore(reducer, preloadedState)
    //     }
    // }
  }
  let subscribe_fns = new Set();
  let state = preloadedState;
  function getState() {
    return state;
  }
  function subscribe(listener_fn) {
    subscribe_fns.add(listener_fn);
    //  返回一个取消订阅的方法
    return function unSubscribe() {
      const index = subscribe_fns.indexOf(listener_fn);
      subscribe_fns.splice(index, 1);
    };
  }
  function dispatch(action) {
    state = reducer(state, action);
    for (let fn of subscribe_fns) {
      fn();
    }
  }

  //   初始化state
  dispatch({});
  return {
    getState,
    subscribe,
    dispatch,
  };
}
